package com.wind.ipagent.service;


import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class IpWhiteService {
    private static String localIp;

    @Autowired
    private KdlService kdlService;

    @Scheduled(fixedDelay = 600 * 1000, initialDelay = 1000)
    public void scheduledGetIp() {
        localIp = getServerIP();
        try {
            if (kdlService.getDpsClient() != null) {
                String[] dpsIpWhitelist = kdlService.getDpsIpWhitelist();
                if(!containsElement(dpsIpWhitelist,localIp)){
                    kdlService.setDpsIpWhitelist(addElementToEnd(dpsIpWhitelist,localIp));
                }
            }
            if (kdlService.getKpsClient() != null) {
                String[] dpsIpWhitelist = kdlService.getKpsIpWhitelist();
                if(!containsElement(dpsIpWhitelist,localIp)){
                    kdlService.setKpsIpWhitelist(addElementToEnd(dpsIpWhitelist,localIp));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static String getServerIP() {
        String ip = "";
        String pageUrl = "https://dev.kdlapi.com/testproxy";
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        CloseableHttpClient httpclient = HttpClients.custom().build();
        try {
            URL url = new URL(pageUrl);
            HttpHost target = new HttpHost(url.getHost(), url.getDefaultPort(), url.getProtocol());
            RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).setConnectionRequestTimeout(20000).build();
            HttpGet httpget = new HttpGet(url.getPath());
            httpget.setConfig(config);
            httpget.addHeader("Accept-Encoding", "gzip"); // 使用gzip压缩传输数据让访问更快
            httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36");
            CloseableHttpResponse response = httpclient.execute(target, httpget);
            try {
                String responseString = EntityUtils.toString(response.getEntity());
                ip = getRexIp(responseString);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ip;
    }

    public static String getRexIp(String ipString) {
        String ip = "";
        String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

        Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
        Matcher matcher = pattern.matcher(ipString);
        while (matcher.find()) {
            ip = matcher.group();
        }
        return ip;
    }

    public boolean containsElement(String[] array, String target) {
        for (String element : array) {
            if (element.equals(target)) {
                return true; // 如果找到目标元素，则返回true
            }
        }
        return false; // 如果未找到目标元素，则返回false
    }

    public String[] addElementToEnd(String[] array, String element) {
        String[] newArray = new String[array.length + 1];
        System.arraycopy(array, 0, newArray, 0, array.length);
        newArray[array.length] = element; // 将新元素放置在新数组的最后一个位置
        return newArray;
    }
}
